// import io from 'socket.io-client'
import store from '@/store'
import axios from '@/until/fetch'
import $ from 'jquery'

const CHAT = {
  socket: null,
  chatList: [],
  onmessageList: [],
  sendText: '',
  init() {
    const url = `${store.state.socketURL}/api/ChatRoom/ConnChatRoom?token=Bearer ${store.state.token}`
    this.socket = new WebSocket(url)
    // const url = `${store.state.socketURL}?token=Bearer ${store.state.token}`
    // this.socket = io.connect(url, { path: '/api/ChatRoom/ConnChatRoom' })
    // this.socket.onopen = () => {
    //   this.socket.send('1234')
    //   console.log('open')
    // }
    this.socket.onmessage = (evt) => {
      const newData = JSON.parse(evt.data)
      const item = {
        UserID: newData.UserIDFrom,
        FNickName: newData.NickName,
        FAddTime: newData.SendTime,
        FID: newData.FID,
        FContent: newData.Content,
        FTelLink: newData.FTelLink
      }
      this.onmessageList = this.onmessageList.concat(item)
    }
    this.getChatList()
    // this.socket.send('hello world!')
    // this.socket.on('message', (data) => {
    //   console.log(data)
    // })
    // this.socket.on('connect', (data) => {
    //   console.log('open')
    // })

    // this.socket.on('disconnect', () => {
    //   console.log('与服务其断开')
    // })

    // this.socket.on('reconnect', () => {
    //   console.log('重新连接到服务器')
    // })
  },
  getChatList(callback) {
    const thisTime = { timeStamp: store.state.fristTime }
    axios.get('/api/ChatRoom/GetLogByTime', thisTime)
      .then((response) => {
        const res = response.data
        if (res.code == 1) {
          if (thisTime.timeStamp == '') {
            this.chatList = res.object
          } else {
            callback && callback(res)
          }
        }
      })
      .catch((err) => {
        console.log(err)
      })
  },
  getNow(time) {
    time = time.replace('T', ' ')
    const arr = time.split(/[- :]/)
    const _date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5])
    store.commit('updateChatTime', Date.parse(_date))
  }
}
export default CHAT
